axios.defaults.baseURL = "http://api-breakingnews-web.itheima.net";

//请求拦截器
axios.interceptors.request.use(
    function (config) {
        //给 /my 开头的添加请求 身份认证信息
        //console.log(config);
        if (config.url.includes("/my/")) {
            config.headers.Authorization = localStorage.getItem("token");
        }
        //返回值
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);
//响应拦截器

axios.interceptors.response.use(
    function (response) {
        let obj = response.data;
        if (obj.message === "身份认证失败！") {
            location.href = "/login.html";
            localStorage.removeItem("token");
        }
        return response;
    },
    function (error) {
        return Promise.reject(error);
    }
);

//格式化日期
function dateFormat(str) {
    let dt = new Date(str)
    let yy = padZero(dt.getFullYear())
    let mm = padZero(dt.getMonth() + 1)
    let dd = padZero(dt.getDate())

    let h = padZero(dt.getHours())
    let m = padZero(dt.getMinutes())
    let s = padZero(dt.getSeconds())
    return `${yy}-${mm}-${dd} ${h}:${m}:${s}`;
}

//补零函数
function padZero(n) {
    return n < 10 ? '0' + n : n
}
